package cn.itsource.mq.transaction;

import cn.itsource.mq.transaction.listener.MyTransactionListener;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.HashMap;

/**
 * 事务消息
 */
public class TransactionProducer {
    public static void main(String[] args) throws Exception{
        //1创建生产者实例                                                  这个是唯一的生产者的组名
        TransactionMQProducer producer = new TransactionMQProducer("mq-tran-producer-group");
        producer.setNamesrvAddr("127.0.0.1:9876");//2设置mq地址 连接nameServer的ip和端口号
        //设置事务监听器
        producer.setTransactionListener(new MyTransactionListener());

        producer.start();//3启动生产者  需要抛异常
        //4发送消息前需要创建   三个参数  topic 消息的分类一级分类  tag二级分类  body是实际需要发送的消息

        byte[] msgByteArray = "事务消息".getBytes(RemotingHelper.DEFAULT_CHARSET);
        Message message = new Message("tran-topic", "tran-tag",msgByteArray);

        HashMap<String, String> map = new HashMap<>();
        map.put("1","一");
        map.put("2","二");
        map.put("3","三");

        SendResult sendResult = producer.sendMessageInTransaction(message,map);//5调用方法发送消息
        System.out.println(sendResult);
        producer.shutdown();//6关闭资源

    }
}
